from django.contrib import admin
from django.http import HttpResponseRedirect
from django.urls import path
from django.shortcuts import render
from django.contrib import messages
from .models import Category, Product, Order
from .services_enhanced import ebay_service
import logging

logger = logging.getLogger(__name__)

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'ebay_category_id', 'parent', 'is_active')
    list_filter = ('is_active', 'parent')
    search_fields = ('name', 'ebay_category_id')
    
    def sync_products(self, request, queryset):
        """同步选中分类的商品"""
        try:
            for category in queryset:
                # 获取分类下的商品
                products = Product.objects.filter(category=category)
                
                for product in products:
                    try:
                        # 更新商品信息
                        ebay_service.update_inventory_item(
                            product.sku,
                            {
                                'product': {
                                    'title': product.name,
                                    'description': product.description,
                                    'aspects': product.aspects,
                                    'imageUrls': product.image_urls
                                },
                                'condition': product.condition,
                                'packageWeightAndSize': product.package_info,
                                'availability': {
                                    'shipToLocationAvailability': {
                                        'quantity': product.quantity
                                    }
                                },
                                'price': {
                                    'value': str(product.price),
                                    'currency': 'CAD'
                                }
                            }
                        )
                        messages.success(request, f'成功同步商品: {product.name}')
                    except Exception as e:
                        logger.error(f"同步商品失败 {product.name}: {e}")
                        messages.error(request, f'同步商品失败 {product.name}: {str(e)}')
                        
        except Exception as e:
            logger.error(f"同步分类商品失败: {e}")
            messages.error(request, f'同步分类商品失败: {str(e)}')
    
    sync_products.short_description = "同步选中分类的商品"
    actions = [sync_products]

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ('name', 'sku', 'category', 'price', 'quantity', 'is_active')
    list_filter = ('is_active', 'category')
    search_fields = ('name', 'sku', 'description')
    
    def sync_to_ebay(self, request, queryset):
        """同步选中商品到eBay"""
        try:
            for product in queryset:
                try:
                    # 更新商品信息
                    ebay_service.update_inventory_item(
                        product.sku,
                        {
                            'product': {
                                'title': product.name,
                                'description': product.description,
                                'aspects': product.aspects,
                                'imageUrls': product.image_urls
                            },
                            'condition': product.condition,
                            'packageWeightAndSize': product.package_info,
                            'availability': {
                                'shipToLocationAvailability': {
                                    'quantity': product.quantity
                                }
                            },
                            'price': {
                                'value': str(product.price),
                                'currency': 'CAD'
                            }
                        }
                    )
                    messages.success(request, f'成功同步商品: {product.name}')
                except Exception as e:
                    logger.error(f"同步商品失败 {product.name}: {e}")
                    messages.error(request, f'同步商品失败 {product.name}: {str(e)}')
                    
        except Exception as e:
            logger.error(f"同步商品失败: {e}")
            messages.error(request, f'同步商品失败: {str(e)}')
    
    sync_to_ebay.short_description = "同步选中商品到eBay"
    actions = [sync_to_ebay]

@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    list_display = ('order_id', 'status', 'created_at', 'updated_at')
    list_filter = ('status', 'created_at')
    search_fields = ('order_id', 'buyer_username')
    
    def sync_from_ebay(self, request, queryset):
        """从eBay同步选中订单"""
        try:
            for order in queryset:
                try:
                    # 获取订单详情
                    order_data = ebay_service.get_order_details(order.order_id)
                    
                    # 更新订单信息
                    order.status = order_data['orderStatus']
                    order.buyer_username = order_data['buyer']['username']
                    order.total_price = order_data['pricingSummary']['total']['value']
                    order.save()
                    
                    messages.success(request, f'成功同步订单: {order.order_id}')
                except Exception as e:
                    logger.error(f"同步订单失败 {order.order_id}: {e}")
                    messages.error(request, f'同步订单失败 {order.order_id}: {str(e)}')
                    
        except Exception as e:
            logger.error(f"同步订单失败: {e}")
            messages.error(request, f'同步订单失败: {str(e)}')
    
    def update_shipping(self, request, queryset):
        """更新选中订单的物流信息"""
        try:
            for order in queryset:
                try:
                    # 更新物流信息
                    ebay_service.update_order_status(
                        order.order_id,
                        {
                            'lineItems': [{
                                'lineItemId': item.line_item_id,
                                'quantity': item.quantity
                            } for item in order.items.all()],
                            'shippedDate': order.shipped_date.isoformat(),
                            'trackingNumber': order.tracking_number,
                            'shippingCarrierCode': order.shipping_carrier
                        }
                    )
                    
                    messages.success(request, f'成功更新物流信息: {order.order_id}')
                except Exception as e:
                    logger.error(f"更新物流信息失败 {order.order_id}: {e}")
                    messages.error(request, f'更新物流信息失败 {order.order_id}: {str(e)}')
                    
        except Exception as e:
            logger.error(f"更新物流信息失败: {e}")
            messages.error(request, f'更新物流信息失败: {str(e)}')
    
    sync_from_ebay.short_description = "从eBay同步选中订单"
    update_shipping.short_description = "更新选中订单的物流信息"
    actions = [sync_from_ebay, update_shipping]
    
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('sync-all-orders/', self.sync_all_orders, name='sync-all-orders'),
        ]
        return custom_urls + urls
    
    def sync_all_orders(self, request):
        """同步所有订单"""
        try:
            # 获取所有订单
            orders_data = ebay_service.get_orders()
            
            for order_data in orders_data.get('orders', []):
                order_id = order_data['orderId']
                order, created = Order.objects.get_or_create(order_id=order_id)
                
                # 更新订单信息
                order.status = order_data['orderStatus']
                order.buyer_username = order_data['buyer']['username']
                order.total_price = order_data['pricingSummary']['total']['value']
                order.save()
            
            messages.success(request, '成功同步所有订单')
        except Exception as e:
            logger.error(f"同步所有订单失败: {e}")
            messages.error(request, f'同步所有订单失败: {str(e)}')
        
        return HttpResponseRedirect("../") 